package com.huawei.cloudapp.common;

import static android.content.Context.MODE_PRIVATE;

import android.content.SharedPreferences;
import android.util.Log;

import java.util.Arrays;

public class CasHistory {

    private SharedPreferences mPreferences;

    public CasHistory(SharedPreferences preferences) {
        mPreferences = preferences;
    }

    public String[] getHistory(String key) {
        String[] keyHistoryList = {};
        String keyHistoryListStr = mPreferences.getString(key, "");
        if (!keyHistoryListStr.isEmpty()) {
            keyHistoryList = keyHistoryListStr.replace(" ", "").split(",");
        }
        if (keyHistoryList.length > 10) {
            String[] newArrays = new String[10];
            System.arraycopy(keyHistoryList, 0, newArrays, 0, 10);
            keyHistoryList = newArrays;
        }
        return keyHistoryList;
    }

    public void setHistory(String key, String value) {
        String[] keyHistoryList = mPreferences.getString(key, "").split(",");
        if (keyHistoryList.length > 10) {
            String[] newArrays = new String[10];
            System.arraycopy(keyHistoryList, 0, newArrays, 0, 10);
            keyHistoryList = newArrays;
        }
        if (!Arrays.asList(keyHistoryList).contains(value)) {
            String keyHistoryListStr = Arrays.toString(keyHistoryList).replace(" ", "");
            StringBuilder sb = new StringBuilder(keyHistoryListStr.substring(1, keyHistoryListStr.length() - 1));
            sb.insert(0, value + ",");
            mPreferences.edit().putString(key, sb.toString()).apply();
        }
    }

}
